import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { localStorage } from '@/utils/storage';
import useStore from '@/store';
// @ts-ignore
import {TOKEN,LANGUAGE} from '@/constant.d.ts';


// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
});

// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (!config.headers) {
      throw new Error(
        `Expected 'config' and 'config.headers' not to be undefined`
      );
    }
    const { user } = useStore();
    if (user.token) {
      config.headers[TOKEN] = `${localStorage.get(TOKEN)}`;
    }
    // 设置语言请求头
    config.headers[LANGUAGE] = `${localStorage.get(LANGUAGE)}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, msg } = response.data;
    if (code === 2000) {
      return response.data;
    } else {
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }

      ElMessage({
        message: msg || '系统出错',
        type: 'error',
      });
      return Promise.reject(new Error(msg || 'Error'));
    }
  },
  (error) => {
    if (401 === error.response.status || 403 === error.response.status) {
      ElMessage({
        message: '权限不足',
        type: 'error',
      });
      return Promise.reject(new Error('权限不足'));
    } else {
      const { message } = error.response.data;
      ElMessage({
        message: message || '系统出错',
        type: 'error',
      });
      return Promise.reject(new Error(message || 'Error'));
    }
  }
);

// 导出 axios 实例
export default service;
